package com.drivingbarefoot.games.OneFour24;

import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.util.MathUtils;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;

public class Die {
	private int value;

	private int id;
	
	private boolean isKept;

	private boolean isInPlay = true;

	private Body body;

	private AnimatedSprite face;

	private int[] index;

	Vector2 originalPos;
	float originalAngle;

	public Die(Body body, AnimatedSprite face, int[] index, int id) {
		this.body = body;
		this.face = face;
		this.index = index;
		this.id = id;
	}

	public Body GetBody() {
		return body;
	}

	private int GetIndexOfTileWithValue(int value) {
		return index[value];
	}

	public void Roll() {
		if (isKept && isInPlay)
			isInPlay = false;
		
		if (isKept)
			return;

		value = MathUtils.random(1, 6);
		face.stopAnimation(GetIndexOfTileWithValue(value));
	}

	public AnimatedSprite GetFace() {
		return face;
	}

	public boolean isKept() {
		return isKept;
	}

	public void setKept(boolean isKept) {
		this.isKept = isKept;
	}

	public boolean isInPlay() {
		return isInPlay;
	}

	public void setInPlay(boolean isInPlay) {
		this.isInPlay = isInPlay;
	}

	public int getValue() {
		return value;
	}

	public void ToggleKept() {
		isKept = !isKept;

		if (isKept) {
			originalPos = body.getPosition();
			originalAngle = body.getAngle();

			// move to inactive area
			body.setTransform(new Vector2(
					((id * 50.0f)+ 3.0f) / 32.0f, 411.0f / 32.0f), 0);
			body.setAwake(true);
		} else {
			// move back to active area
			body.setActive(false);
			body.setTransform(originalPos.sub(0, 100.0f / 32.0f), originalAngle);
			body.setAwake(true);
			body.setActive(true);
		}

	}

	public void Reset() {
		body.setActive(false);
		body.setTransform(new Vector2(MathUtils.random(50.0f, 190.0f) / 32.0f,
				MathUtils.random(50.0f, 400.0f) / 32.0f), originalAngle);
		body.setAwake(true);
		body.setActive(true);

		originalPos = null;
		originalAngle = 0;

		isInPlay = true;
		isKept = false;

		value = 0;
	}
}
